<?php

namespace App\Services\Order\AfterSale;

use App\Models\AfterSaleOrder;
use App\Models\Base;
use App\Models\Order;

class MakeUp extends PlaceAfterSaleOrder
{
    public function handle($order = null)
    {
        $agentId = \Auth::user()['id'];
        if (AfterSaleOrder::query()
            ->where([
                'agent_id' => $agentId,
                'order_id' => $order['id'],
                'type' => AfterSaleOrder::TYPE_MAKE_UP,
            ])
            ->whereIn('status', [AfterSaleOrder::STATUS_PENDING_REVIEW, AfterSaleOrder::STATUS_FOLLOWING_UP, AfterSaleOrder::STATUS_PASSED])
            ->exists()) {

            abort(400, '该订单已经申请过补偿,不可再次提交');
        }

        $afterSaleOrder = AfterSaleOrder::query()->create([
            'agent_id' => $agentId,
            'supplier_id' => $order['commodity_snapshot']['supplier_id'],
            'order_id' => $order['id'],
            'order_numbering' => $order['numbering'],
            'numbering' => $this->makeOrderNumbering('BC'),
            'type' => AfterSaleOrder::TYPE_MAKE_UP,
            'compensation' => ($this->request['compensation'] ?? 0) * Base::CURRENCY_UNIT_CONVERSION,
            'reason' => $this->request['reason'] ?? '',
            'commodity_id' => $order['commodity_id'],
            'commodity_activity_id' => $order['commodity_activity_id'],
            'client_id' => $order['client_id'],
        ]);

        // 附件 凭证
        $afterSaleOrder->attachments()->sync($this->request['picture_certificate'] ?? []); // 图片
        $temp = [];
        foreach ($this->request['video_certificate'] ?? [] as $attachmentId) {
            $temp[$attachmentId] = ['type' => AfterSaleOrder::ATTACHMENT_TYPE_VIDEO];
        }
        $afterSaleOrder->attachments()->syncWithoutDetaching($temp); // 视频, 这里用 syncWithoutDetaching 不清除上面的图片 ID
    }
}
